﻿using Common;
using Common.Complete;
using IService;
using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Model;
using Model.Models;
using ModelDto;
using ModelDto.Request.SysTableDto;
using NetTaste;
using NPOI.OpenXmlFormats.Spreadsheet;
using Service;
using System.Reflection;

namespace AssetManegement.Controllers
{
    /// <summary>
    /// 登录
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {



        private readonly IAccountService _accountService;
        private readonly IRoleMenuActionService _roleMenuActionService;
        private readonly IRedisHelper _redisHelper;
        private readonly IOptions<AppsettingConfig> _AppConfig;


        private readonly ILogService _logService;
    
        private readonly ICaptcha _captcha;

        public LoginController(IAccountService accountService, IRedisHelper redisHelper
            , IRoleMenuActionService roleMenuActionService, IOptions<AppsettingConfig> AppConfig
            , ILogService logService,
             ICaptcha _captcha)
        {
            this._captcha = _captcha;
            _accountService = accountService;
            _redisHelper = redisHelper;
            _roleMenuActionService = roleMenuActionService;
            _AppConfig = AppConfig;

            _logService = logService;
        }
        //public class Ceshi
        //{
        //    public IFormFile file { get; set; }
        //    public string additionalParam { get; set; }
        //}
        //[HttpPost]
        //public void UploadFile([FromForm] Ceshi ceshi)
        //{
        //    Console.WriteLine("!23");
        //}
        
        [HttpPost]
        public IActionResult Captcha(CaptchaRequest request)
        {
            var info = _captcha.Generate(request.Id, 60);

            var stream = new MemoryStream(info.Bytes);
            return File(stream, "image/gif");
        }
        /// <summary>
        /// 演示时使用HttpGet传参方便，这里仅做返回处理
        /// </summary>
        //[HttpPost]
        //public bool Validate(CaptchaValidateRequest request)
        //{
        //    return _captcha.Validate(request.Id, request.Code);
        //}

       









        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> Login(AccountLoginRequest request)
        {
            JsonResultL response = new JsonResultL();
            if (!_captcha.Validate(request.Id, request.VerificationCode))
            {
                return response.Fail("验证码错误或已过期，请重试");
            }

            if (string.IsNullOrWhiteSpace(request.AccountNo) || string.IsNullOrWhiteSpace(request.Pwd))
            {
                _logService.WriteLoginLog(null, request.AccountNo, request.Pwd, "登录失败", "账号密码");
                return response.Fail("登录失败，账号密码不能为空");
            }

            string checkRes = CheckUserLogin(request.AccountNo);

            if (!string.IsNullOrWhiteSpace(checkRes))
            {
                _logService.WriteLoginLog(null, request.AccountNo, request.Pwd, checkRes, "账号密码");
                UserLoginError(request.AccountNo);
                return response.Fail(checkRes);
            }

            Account account = await _accountService.QueryAsync(a => a.AccountNo == request.AccountNo);
            if (account == null)
            {
                _logService.WriteLoginLog(null, request.AccountNo, request.Pwd, "登录失败", "账号密码");
                UserLoginError(request.AccountNo);
                return response.Fail("登录失败");
            }

            string pwd = MD5Helper.Md5Encrypt(request.Pwd);

            if (account.Pwd != pwd)
            {
                _logService.WriteLoginLog(account, request.AccountNo, request.Pwd, "登录失败", "账号密码");
                UserLoginError(request.AccountNo);
                return response.Fail("登录失败");
            }
            if (account.EnableState != 1)
            {
                _logService.WriteLoginLog(account, request.AccountNo, request.Pwd, "账户已失效", "账号密码");
                UserLoginError(request.AccountNo);
                return response.Fail("账户已失效");
            }

            (string token, string powerStr) = await UserLoginSuccess(account);

            if (!string.IsNullOrWhiteSpace(token))
            {
                _logService.WriteLoginLog(account, request.AccountNo, request.Pwd, "登录成功", "账号密码");
                return response.Sucess(new { Token = token, Name = account.Name, AccountNo = account.AccountNo, Power = powerStr }, "登录成功");
            }
            _logService.WriteLoginLog(account, request.AccountNo, request.Pwd, "系统异常", "账号密码");
            UserLoginError(request.AccountNo);
            return response.Fail("系统异常");
        }


        /// <summary>
        /// 检查账号是否可以登录
        /// </summary>
        /// <param name="accounntNo"></param>
        /// <returns></returns>
        private string CheckUserLogin(string accounntNo)
        {
            var res = _redisHelper.GetValue($"{ConstBase.Cache_UserLogin}{accounntNo}");

            if (string.IsNullOrWhiteSpace(res))
            {
                return "";
            }
            int count = 0;
            int.TryParse(res, out count);

            if (count > 6)
            {
                return "密码输错次数过多，稍后再试";
            }
            return "";
        }

        /// <summary>
        /// 登录成功
        /// </summary>
        /// <param name="account"></param>
        /// <param name="powerStr"></param>
        /// <returns></returns>
        private async Task<(string, string)> UserLoginSuccess(Account account)
        {
            string powerStr = "";
            AccountLoginInfo accountLoginInfo = new AccountLoginInfo();

            accountLoginInfo.Account = account;
            accountLoginInfo.PowerCode = "-1";


            //获取权限
            //if (!(account.AccountNo == "admin" && account.Id == "accountaaaaaaaaaaaaaaaaaaaaaaaaa"))
            if (account.IsSysTem != 1)
            {
                accountLoginInfo.PowerCode = await _roleMenuActionService.GetUserPowerCode(account.Id);

            }
            powerStr = accountLoginInfo.PowerCode;

            string token = Guid.NewGuid().ToString("N").ToUpper();

            _redisHelper.SetValue(token, Newtonsoft.Json.JsonConvert.SerializeObject(accountLoginInfo), new TimeSpan(2, 0, 0));


            var res = _redisHelper.GetValue($"{ConstBase.Cache_UserLogin}{account.AccountNo}");

            if (!string.IsNullOrWhiteSpace(res))
            {
                _redisHelper.SetValue($"{ConstBase.Cache_UserLogin}{account.AccountNo}", "0", new TimeSpan(2, 0, 0));
            }


            return new(token, powerStr);
        }

        /// <summary>
        /// 登录失败
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        private void UserLoginError(string account)
        {
            var res = _redisHelper.GetValue($"{ConstBase.Cache_UserLogin}{account}");

            if (string.IsNullOrWhiteSpace(res))
            {
                _redisHelper.SetValue($"{ConstBase.Cache_UserLogin}{account}", "1", new TimeSpan(0, 2, 0));
            }
            else
            {
                int count = 0;
                int.TryParse(res, out count);

                _redisHelper.SetValue($"{ConstBase.Cache_UserLogin}{account}", (count + 1).ToString(), new TimeSpan(0, 2, 0));
            }


        }

    }
}
